import 'dart:convert';
import 'dart:io';

import 'package:fast_gbk/fast_gbk.dart';
import 'package:file_picker/file_picker.dart';

import '../../helpers/database_helper.dart';






Future<File?> _pickFile() async {
  // 打开文件选择器
  FilePickerResult? result = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: ['txt'], // 只允许选择 .txt 文件
  );

  if (result != null) {
    String path = result.files.single.path!;
    File file = File(path); // 获取文件路径
    return file;
  } else {
    // 用户取消选择
    return null;
  }
}

Future<String> readFileWithEncoding(File file) async {
  final bytes = await file.readAsBytes();

  bool checkGarbled(String subContent) {
    final garbledPattern = RegExp(r'Õ|Ê|Ç|³|¾|Ð|Ó|Î|Á|É|�');

    final lines = subContent.split('\n');
    final sampleLines = lines.take(lines.length > 100 ? 100 : lines.length);
    return sampleLines.any((line) => garbledPattern.hasMatch(line));
  }

  // UTF-8 测试
  try {
    String contentUtf8 = utf8.decode(bytes, allowMalformed: true); // 使用 allowMalformed: true 来容忍一些格式错误的 UTF-8 序列
    if (!checkGarbled(contentUtf8)) {
      return contentUtf8;
    }
  } catch (e) {
    // 忽略 UTF-8 解码错误
  }

  // GBK 解码
  try {
    String contentGBK = gbk.decode(bytes, allowMalformed: true);
    if (!checkGarbled(contentGBK)) {
      return contentGBK;
    }
  } catch (e) {
    // 捕获并处理 GBK 解码错误
  }

  // 如果两种编码都失败，返回错误信息
  return '无法解码文件，可能是未知编码或文件损坏。';
}



Future<void> convertFromTxt() async {
  File? file = await _pickFile();
  if(file == null) return;

  final dbHelper = DatabaseHelper();

  var filename = file.path.split('/').last;

  filename =
      filename.split('.').sublist(0, filename.split('.').length - 1).join('.');
  final titleString =
      RegExp(r'(?<=《)[^》]+').firstMatch(filename)?.group(0) ?? filename;

  final authorString =
      RegExp(r'(?<=作者：).*').firstMatch(filename)?.group(0) ?? 'Unknown';

  int currentBook;
  currentBook = await dbHelper.insertBook({'title': titleString, 'author': authorString});

  // read file
  String content = await readFileWithEncoding(file);
  final patternStr = RegExp(
    r'^(?:(.+ +)|())(第[一二三四五六七八九十零〇百千万两0123456789]+[章卷]|卷[一二三四五六七八九十零〇百千万两0123456789]+|chap(?:ter)\.?|vol(?:ume)?\.?|book|bk)(?:(?: +.+)?|(?:\S.*)?)$',
    multiLine: true,
    caseSensitive: false,
  );

  // 分割文章内容
  List<String> sections = [];
  int lastMatchEnd = 0;

  for (final match in patternStr.allMatches(content)) {
    if (match.start > lastMatchEnd) {
      // 提取未匹配的部分（如果有）
      sections.add(content.substring(lastMatchEnd, match.start).trim());
    }
    // 提取匹配的部分
    String matchedSection = content.substring(match.start, match.end).trim();
    sections.add(matchedSection);
    lastMatchEnd = match.end;
  }

  // 如果最后还有未匹配的部分，添加到列表中
  if (lastMatchEnd < content.length) {
    sections.add(content.substring(lastMatchEnd).trim());
  }

  // 存储分割结果
  await dbHelper.insertChapter({'book_id': currentBook, 'title': "前言", 'content': sections[0]});

  for (int i = 1; i < sections.length; i+=2) {
    await dbHelper.insertChapter({'book_id': currentBook, 'title': sections[i], 'content': sections[i+1]});
  }
}
